const Book = require("../models/book");
const {
    Op
} = require("sequelize");
exports.addBook = async function (bookObj) {
    const ins = await Book.create(bookObj);
    return ins.toJSON()
};

exports.delBook = async function (id) {
    const ins = await Book.destroy({
        where: {
            id
        }
    })
    return ins
}

exports.updateBook = async function (id, updateObj) {
    const ins = await Book.update(updateObj, {
        where: {
            id
        }
    })
    return ins
}

exports.getBookByName = async function (name, fuzzy = false) {
    // 默认模糊查询为false
    if (!fuzzy) {
        const res = await Book.findOne({
            where: {
                bookName: name
            }
        })
        return JSON.parse(JSON.stringify(res))
    }
    else{
        const res = await Book.findAll({
            where:{
                bookName:{
                    [Op.like]:`%${name}%`
                }
            }
        })
        return JSON.parse(JSON.stringify(res))
    }
}

exports.getBooks=async function(page=1,size=5){
    const {count,rows} = await Book.findAndCountAll({
        offset:(page-1)*size,
        limit:size
    })
    return {
        total:count,
        datas:JSON.parse(JSON.stringify(rows))
    }
}